(function(win,$) {
    'use strict';
    /**
     * zhx swf player plugin ver 1.0
     * Author: Vicco Wang
     * Date : 2017/05/22
     *
     * ZhxPlayer External API :
     *
     * - setup( userOptions )           initial ZhxPlayer option and return the ZhxPlayer Object
     * - play()                         播放
     * - remove()                       移除
     * - getContainer()                 return flashObject <object />
     * - on(listenerType, callback )    注册监听事件
     * - getState()                     获取播放状态
     * - setMute( boolean )             设置静音
     *
     *
     * zhx.player.swf
     * Author : Null
     * Date : 2017/05/22
     *
     * flashPlayer.swf Internal API:
     *
     * - setMute( boolean )     true/false 是否静音
     * - setVolume( Number )    0 - 1  音量大小
     * - remove()               移除
     * - getState()             播放状态 @return string
     * - getVideo()             获取播放器长宽
     * - setRatio(widthRatio, heightRatio)  设置播放比 默认4:3 设置16:9 这需要配置为 setRatio(16,9);
     *
     *
     * Dependencies:
     * jQuery
     * SWFObject 2.2
     *
     */

    /**
     * flash to JS global API
     * @private
     */
    var __ZhxPlayerFlashUrl = null,
        __ZhxPlayerFlashName = null;
    //需要给全局一个接口
    win.__zhxOnVideoInitialized = function (){
        return  __ZhxPlayerFlashUrl + "," + __ZhxPlayerFlashName;
    };

    var ZhxPlayer = win.ZhxPlayer = function(domElement) {

        if (!(this instanceof ZhxPlayer)) return new ZhxPlayer( domElement );

        if( !swfobject ) throw 'please load swfobject.js before create ZhxPlayer.';

        var zhxSWFObject = null;

        //ZhxPlayer normal options
        var playerOptions = {
            player      : 'zhx.player.swf',
            file : "",
            name : "",
            autoStart   : true,
            controls    : false,
            screenRatio : "4:3",
            width       : '100%',
            height      : '100%',
            mute        : true
        };

        //ZhxPlayer 已注册的监听对象
        var listenerHandle = {};

        /**
         * 创建一个随机ID
         * @private
         */
        function __createId(prefix){
            var date,seed,char,randomChar="",string;
            date = new Date().getTime();
            seed = parseInt( Math.random(1,1000) * 1000 );
            char = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
            for( var i = 0 ; i < 5; i++ ){
                randomChar += char.charAt(Math.floor(Math.random() * 52));
            }
            string = String(seed + date) + randomChar;
            return prefix + '-' + string.substr(5);
        }

        /**
         * 通过swfobject生成一个swf object
         * @param domElement
         * @param options
         * @private
         */
        function __createSWFObject(domElement,options) {
            /**
             * FlashPlayer base params
             */
            var swfVersion = "11.1.0",
                xiSwfUrlStr = "playerProductInstall.swf",
                flashvars = {},
                flashParams = {
                    quality : 'Best',
                    bgcolor : '#222222',
                    allowscriptaccess : 'always',
                    allowfullscreen : 'true',
                    scale : 'Showall',
                    wmode : 'window'
                },
                attributes = {
                    id      : options.id,
                    name    : options.id,
                    align   : "middle"
                };

            //配置当前对象全局变量
            __ZhxPlayerFlashUrl = options.file;
            __ZhxPlayerFlashName = options.name;

            //这里生成临时DOM为swfObject创建FlashObject使用
            var swfDom = $("<div />");
                swfDom[0].id = __createId("zhx-player-container");
             if( domElement ){
                 $(domElement).append( swfDom );
                 $(domElement).appendTo('body');
             }
            //创建swfObject
            swfobject.embedSWF(options.player,swfDom[0].id,options.width,options.height,swfVersion,xiSwfUrlStr,flashvars,flashParams,attributes,createCallback);
            //创建成功后,将结果赋值给当前全局对象zhxSWFObject;
            function createCallback(res){
                zhxSWFObject = res;
                //执行状态监控
                getFlashPlayState(options);
                //移除临时DOM对象
                $(domElement).remove();
            }

        }

        /**
         * Flash播放后,内置方法才可调用,所以,有些事情需要在swfObject初始化完毕后,但flash内置方法扔不可用之前做些事情
         * TODO 这里日后可以做个延迟判断播放是否加载失败,比如interval time 到了15秒仍然无有效状态,则提示用户播放失败
         * @param options
         */
        function getFlashPlayState(options){
            //set an interval to detect the flash state
            var interval = setInterval(function(){
                if( $.type( zhxSWFObject.ref.getState ) === "function" && zhxSWFObject.ref.getState() === "playing" ){
                    //执行beforePlay监听事件回调
                    __excuteListener('beforePlay');
                    //执行play监听事件回调
                    __excuteListener('play');
                    //判断是否配置了显示高宽比
                    if( options.screenRatio === "16:9" ) zhxSWFObject.ref.setRatio(16,9);
                    //清除延迟
                    clearInterval(interval);
                }
            });
        }

        //注册监听事件
        function __registerListener(listenerType, callback){
           if(listenerHandle[listenerType] === undefined ){
               listenerHandle[listenerType] = callback;
           }
        }
        //执行监听函数
        function __excuteListener(type){
            $.each(listenerHandle,function(key,value){
                if( key === type ){
                    value.call(this,zhxSWFObject);
                }
            })
        }
        //合并用户配置项
        function extendOptions(userOptions){
            return $.extend({}, playerOptions, userOptions);
        }

        /**
         * return public methods
         */
        return {
            /**
             * 创建
             * @param userOptions
             * @returns {win.ZhxPlayer}
             */
            setup : function( userOptions ){

                var opts = extendOptions(userOptions);

                __createSWFObject(domElement, opts);

                return this;

            },
            /**
             * 该方法会直接返回Flash Object Dom
             * @returns {*}
             */
            getContainer : function(){
                if( !$.isPlainObject(zhxSWFObject) ) throw 'zhxSWFObject created failure. please check your custom options';
                return zhxSWFObject.ref;
            },
            /**
             * 监听方法
             * @param type
             * @param callback
             */
            on : function( type, callback ){
                __registerListener(type,callback);
            },
            /**
             * 播放方法,目前Flash组件为自动播放
             */
            play : function(){
                //call on listener
                __excuteListener('play');
            },

            remove : function(){
                //call swf method
                zhxSWFObject.ref.remove();
                //call on listener
                __excuteListener('remove');
            },

            getState : function(){
               //call swf method
               if( $.type( zhxSWFObject.ref.getState ) === "function" ) return zhxSWFObject.ref.getState();
            },

            //设置静音 true / false
            setMute : function(isMute){
                //call swf method
                if( $.type( zhxSWFObject.ref.getState ) === "function" )  zhxSWFObject.ref.setMute(isMute);
            }

        }

    };

    ZhxPlayer.prototype = {

    };

})(window,jQuery);



